package xin.alum.aim.coder;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelPipeline;
import io.netty.handler.codec.json.JsonObjectDecoder;
import io.netty.util.CharsetUtil;

import java.util.ArrayList;
import java.util.List;

/**
 * JSON到Sent的解码转换
 *
 * @author Alum(alum @ live.cn)
 * @date 2021/8/5 17:05
 */
public class JsonDecoder extends JsonObjectDecoder {

    @Override
    protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> list) {
        ChannelPipeline pipeline = ctx.channel().pipeline();
        try {
            super.decode(ctx, in, list);
            if (!list.isEmpty()) {
                List<String> out = new ArrayList<>();
                list.forEach(p -> out.add(((ByteBuf) p).toString(CharsetUtil.UTF_8)));
                list.clear();
                list.addAll(out);
            }
        } catch (Exception e) {
            pipeline.remove(this);
            ctx.fireChannelRead(in);
        }
    }
}
